<template>
  <Modal v-model="isShow"
         footer-hide
         @on-cancel="closeEvent"
         :mask-closable="false"
         title="修改密码">
    <Form ref="form" :label-width="80" :model="formData" :rules="rules">
      <FormItem label="原密码" prop="oldPassword">
        <Input placeholder="请输入当前登陆密码" type="password" password
               v-model="formData.oldPassword"/>
      </FormItem>
      <FormItem label="新密码" prop="newPassword">
        <Input placeholder="请输入新密码" type="password" password
               v-model="formData.newPassword"/>
      </FormItem>
      <FormItem label="重复新密码" prop="reNewPassword">
        <Input placeholder="请再次输入新密码" type="password" password
               v-model="formData.reNewPassword"/>
      </FormItem>
      <FormItem class="form-bottom-btn">
        <Button @click="submitBtnClick" type="primary">修改密码</Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script>

import {RESPONSE_CODE_SUCCESS} from "@/constant/response";
import {Message} from "view-ui-plus";
import {currUserModifyPassword, getCertification} from "@/api/auth/password";
import {logout} from "@/api/auth/auth";
import storage from "@/config/storage";

const formData = {
  oldPassword: '',
  newPassword: '',
  reNewPassword: '',
}

export default {
  data() {
    return {
      isShow: false,
      formData: {},
      rules: {
        oldPassword: [
          {required: true, message: '不能为空', trigger: 'blur'},
        ],
        newPassword: [
          {required: true, message: '不能为空', trigger: 'blur'},
        ],
        reNewPassword: [
          {required: true, message: '不能为空', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {
    logout() {
      logout().then(() => {
      }).finally(() => {
        storage.clear()
      })
      this.$router.push("/login")
    },
    submitBtnClick() {
      if (this.formData.newPassword !== this.formData.reNewPassword) {
        Message.warning("两次密码输入不一致")
        return
      }
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        let saveData = {
          oldPassword: this.formData.oldPassword,
          newPassword: this.formData.newPassword
        }
        getCertification().then(res => {
          if (res.code !== RESPONSE_CODE_SUCCESS) {
            Message.success("证书获取失败")
            return
          }
          currUserModifyPassword(res.data, saveData).then(res => {
            if (res.code == RESPONSE_CODE_SUCCESS) {
              Message.success("修改成功")
              this.isShow = false
              this.logout()
            }
          })
        })
      })
    },
    show() {
      this.formData = this.$utils.clone(formData)
      this.isShow = true
    },
    closeEvent() {
      this.formData = this.$utils.clone(formData)
    },
  }
}
</script>

<style scoped>

</style>
